﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using ScrumTable.Common;
using ScrumTable.Common.FileSystem;

namespace ScrumTable.Config
{

    #region Usings

    

    #endregion

    /// <summary>
    /// Represents the LoginAccountManager xml object serializer.
    /// </summary>
    public class ConfigSerializer<T> 
        where T : class, ISerializationMarker<T>, new()
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        private readonly string _storagePath;
        private readonly string _storageLocalFolder;

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------
        #endregion

        #region Constructors / Destructor

        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Initializes a new instance of the ConfigSerializer class.
        /// </summary>
        /// <param name="storagePath">The storage path.</param>
        /// <param name="storageLocalFolder">a path where all user has access.</param>
        internal ConfigSerializer(string storagePath, string storageLocalFolder)
        {
            PreCondition.AssertNotNull(storagePath, "PreCondition");
            _storagePath = storagePath;
            _storageLocalFolder = storageLocalFolder;
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates the config manager.
        /// </summary>
        /// <returns></returns>
        public T Deserialize()
        {
            T manager;

            if (File.Exists(_storagePath))
            {

                try
                {

                    manager = GetManager(_storagePath);
                }
                catch (Exception)
                {
                    manager = GetManager(_storageLocalFolder);
                }

            }
            else
            {
                manager = new T();
            }
            manager.Serializer = this;
            return manager;
        }

        private T GetManager(string storagePath)
        {
            T manager;
            using (var file = new FileStream(storagePath, FileMode.Open, FileAccess.Read))
            {
                XmlSerializer s = CreateSerializer();
                manager = (T)s.Deserialize(file);
            }
            return manager;
        }

        /// <summary>
        /// Saves the config list.
        /// </summary>
        public void Serialize(T accountManager)
        {
            try
            {
                SaveToFile(accountManager, _storagePath);
            }
            catch (Exception)
            {

                SaveToFile(accountManager, _storageLocalFolder);
            }
            

        }

        private void SaveToFile(T accountManager, string pathToSave)
        {
            using (var file = new StreamWriter(pathToSave))
            {
                XmlSerializer s = CreateSerializer();
                using (MemoryStream stream = new MemoryStream())
                {
                    s.Serialize(stream, accountManager, null);
                    Encoding enc = Encoding.UTF8;
                    string xml = enc.GetString(stream.GetBuffer());
                    file.Write(xml);
                }
            }
        }

        private XmlSerializer CreateSerializer()
        {
            return new XmlSerializer(typeof (T));
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}
